// The Map
var map;
var activeMarker;

// Markers
var cameraIcon = new GIcon();
cameraIcon.image = "mapImages/camera.png";
cameraIcon.iconSize = new GSize(16, 16);
cameraIcon.iconAnchor = new GPoint(8, 8);
cameraIcon.infoWindowAnchor = new GPoint(4, 4);

var redIcon = new GIcon();
redIcon.image = "mapImages/redSquare.png";
redIcon.iconSize = new GSize(8, 8);
redIcon.iconAnchor = new GPoint(4, 4);
redIcon.infoWindowAnchor = new GPoint(4, 4);

//Variables to maintain the state of visited and favourited initialized to 0
var wasVisited = 0;
var wasFavourited = 0; 

function init() 
{
  // Populate badge
  //retrieveUserInfo("1442479765");
  retrieveUserInfo(document.getElementById('userID').value);
  
	if (GBrowserIsCompatible()) 
	{
    var id = getURLParam('id');
    
		// Setup the Map
		map = new GMap2(document.getElementById("divMap"));
		map.addControl(new GLargeMapControl());
		map.enableScrollWheelZoom();
		map.addMapType(G_PHYSICAL_MAP);
		if(id == 0)
		{
      // Get Zip code from facebook or IP Address
      // Reverse Geocode and set tat to point
      var point = new GLatLng(44.976436, -93.232242);
      map.setCenter(point, 15); 
		}
		//map.enableGoogleBar();

		// Load the walk from database
		if(id != 0)
      retrieveWalks(id);
    else
      retrieveUIDWalks(document.getElementById('userID').value);
  }//GBrowser
  else
  {
    alert('You are using incompatible browser!! Use Google Chrome or Mozilla Firefox!');
  }
}//init

function retriveAllWalks()
{
    var request = GXmlHttp.create();
  // Indicate Loading
  request.open('GET', 'mapWalks5.php', true);
  request.onreadystatechange = function() 
  {
    if (request.readyState == 4) 
    {
      // Stop Loading
      if(request.responseText != '<walks></walks>')
      {
        xmlDoc = request.responseXML;
        if(xmlDoc != null)
        {
          walks = xmlDoc.documentElement.getElementsByTagName("walk");
          var i = 0;
          addWalk(walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("pnts"), walks[i].getAttribute("desc"), walks[i].getAttribute("photo"), walks[i].getAttribute("rtng"), walks[i].getAttribute("views"), walks[i].getAttribute("favs"), walks[i].getAttribute("zip"), walks[i].getAttribute("weather"), walks[i].getAttribute("location"), walks[i].getAttribute("slope"));
          updateButtons(walks[i].getAttribute("id"), walks[i].getAttribute("title"), walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("center"), walks[i].getAttribute("pnts"));
          showHideDeleteButton(walks[i].getAttribute("uid"));
          document.getElementById('searchContent').innerHTML += '<div class="listItem" id="listItem"><a href="javascript:updateWalks(' + walks[i].getAttribute("id") + ')" class="link">' + walks[i].getAttribute("title") + '</a></div>';
          
          var tempHTML = document.getElementById('searchContent').innerHTML;
          for (var i = 1 ; i < walks.length; i++) 
          {
            tempHTML += '<div class="listItem" id="listItem"><a href="javascript:updateWalks(' + walks[i].getAttribute("id") + ')" class="link">' + walks[i].getAttribute("title") + '</a></div>';
            //addWalk(walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("pnts"), walks[i].getAttribute("desc"), walks[i].getAttribute("photo"), walks[i].getAttribute("rtng"), walks[i].getAttribute("views"), walks[i].getAttribute("favs"), walks[i].getAttribute("zip"), walks[i].getAttribute("weather"), walks[i].getAttribute("location"), walks[i].getAttribute("slope"));
          }
          document.getElementById('searchContent').innerHTML = tempHTML;
          document.getElementById('numOfWalks').innerHTML = walks.length;
        }
        else
        {
          map.setCenter(new GLatLng(44.976436, -93.232242), 12);
          alert('Error Loading Data from File! Please try again..');
        }
      }
      else
      {
        map.setCenter(new GLatLng(44.976436, -93.232242), 12);
        alert('No walks in system!!! Create one');
      }
    } 
  }
  request.send(null);
}

// Make an ajax call to load the walk..
function retrieveUIDWalks(uid) 
{
  var request = GXmlHttp.create();
  // Indicate Loading
  request.open('GET', 'mapWalks2.php?uid='+uid, true);
  request.onreadystatechange = function() 
  {
    if (request.readyState == 4) 
    {
      // Stop Loading
      if(request.responseText != '<walks></walks>')
      {
        xmlDoc = request.responseXML;
        if(xmlDoc != null)
        {
          walks = xmlDoc.documentElement.getElementsByTagName("walk");
          var i = 0;
          addWalk(walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("pnts"), walks[i].getAttribute("desc"), walks[i].getAttribute("photo"), walks[i].getAttribute("rtng"), walks[i].getAttribute("views"), walks[i].getAttribute("favs"), walks[i].getAttribute("zip"), walks[i].getAttribute("weather"), walks[i].getAttribute("location"), walks[i].getAttribute("slope"));
          updateButtons(walks[i].getAttribute("id"), walks[i].getAttribute("title"), walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("center"), walks[i].getAttribute("pnts"));
          showHideDeleteButton(walks[i].getAttribute("uid"));
          document.getElementById('searchContent').innerHTML += '<div class="listItem" id="listItem"><a href="javascript:updateWalks(' + walks[i].getAttribute("id") + ')" class="link">' + walks[i].getAttribute("title") + '</a></div>';
          
          var tempHTML = document.getElementById('searchContent').innerHTML;
          for (var i = 1 ; i < walks.length; i++) 
          {
            tempHTML += '<div class="listItem" id="listItem"><a href="javascript:updateWalks(' + walks[i].getAttribute("id") + ')" class="link">' + walks[i].getAttribute("title") + '</a></div>';
            //addWalk(walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("pnts"), walks[i].getAttribute("desc"), walks[i].getAttribute("photo"), walks[i].getAttribute("rtng"), walks[i].getAttribute("views"), walks[i].getAttribute("favs"), walks[i].getAttribute("zip"), walks[i].getAttribute("weather"), walks[i].getAttribute("location"), walks[i].getAttribute("slope"));
          }
          document.getElementById('numOfWalks').innerHTML = walks.length;
          document.getElementById('searchContent').innerHTML = tempHTML;
        }
        else
        {
          map.setCenter(new GLatLng(44.976436, -93.232242), 12);
          alert('Error Loading Data from File! Please try again..');
        }
      }
      else
      {
        retriveAllWalks();
      }
    } 
  }
  request.send(null);
}

function updateWalks(id)
{
  var request = GXmlHttp.create();
  // Indicate Loading
  request.open('GET', 'mapWalks.php?id='+id, true);
  request.onreadystatechange = function() 
  {
    if (request.readyState == 4) 
    {
      // Stop Loading
      if(request.responseText != '<walks>-1</walks>')
      {
        xmlDoc = request.responseXML;
        if(xmlDoc != null)
        {
          walks = xmlDoc.documentElement.getElementsByTagName("walk");
          for (var i = 0; i < walks.length; i++) 
          {
            if(walks[i].getAttribute("id") == id){
                map.clearOverlays();
                addWalk(walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("pnts"), walks[i].getAttribute("desc"), walks[i].getAttribute("photo"), walks[i].getAttribute("rtng"), walks[i].getAttribute("views"), walks[i].getAttribute("favs"), walks[i].getAttribute("zip"), walks[i].getAttribute("weather"), walks[i].getAttribute("location"), walks[i].getAttribute("slope"));
                updateButtons(walks[i].getAttribute("id"), walks[i].getAttribute("title"), walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("center"), walks[i].getAttribute("pnts"));
                showHideDeleteButton(walks[i].getAttribute("uid"));
                break;
            }
          }
        }
        else
        {
          map.setCenter(new GLatLng(44.976436, -93.232242), 12);
          alert('Error Loading Data from File! Please try again..');
        }
      }
      else
      {
        map.setCenter(new GLatLng(44.976436, -93.232242), 12);
        alert('Incorrect walk ID! Please check ID and try again!');
      }
    } 
  }
  request.send(null);  
}


// Make an ajax call to load the walk..
function retrieveWalks(id) 
{
  var request = GXmlHttp.create();
  // Indicate Loading
  request.open('GET', 'mapWalks.php?id='+id, true);
  request.onreadystatechange = function() 
  {
    if (request.readyState == 4) 
    {
      // Stop Loading
      if(request.responseText != '<walks>-1</walks>')
      {
        xmlDoc = request.responseXML;
        if(xmlDoc != null)
        {
          walks = xmlDoc.documentElement.getElementsByTagName("walk");
          for (var i = 0; i < walks.length; i++) 
          {
            addWalk(walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("pnts"), walks[i].getAttribute("desc"), walks[i].getAttribute("photo"), walks[i].getAttribute("rtng"), walks[i].getAttribute("views"), walks[i].getAttribute("favs"), walks[i].getAttribute("zip"), walks[i].getAttribute("weather"), walks[i].getAttribute("location"), walks[i].getAttribute("slope"));
            updateButtons(walks[i].getAttribute("id"), walks[i].getAttribute("title"), walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("center"), walks[i].getAttribute("pnts"));
            showHideDeleteButton(walks[i].getAttribute("uid"));
            document.getElementById('searchContent').innerHTML += '<div class="listItem" id="listItem"><a href="javascript:updateWalks(' + walks[i].getAttribute("id") + ')" class="link">' + walks[i].getAttribute("title") + '</a></div>';
          }
          document.getElementById('numOfWalks').innerHTML = walks.length;
        }
        else
        {
          map.setCenter(new GLatLng(44.976436, -93.232242), 12);
          alert('Error Loading Data from File! Please try again..');
        }
      }
      else
      {
        map.setCenter(new GLatLng(44.976436, -93.232242), 12);
        alert('Incorrect walk ID! Please check ID and try again!');
      }
    } 
  }
  request.send(null);
}

function showHideDeleteButton(walkUID)
{
  var UID = document.getElementById('userID').value;
  if( walkUID != UID)
    document.getElementById('delete').style.display = 'none';
  else
    document.getElementById('delete').style.display = 'display';
}

function updateButtons(id, title, walkDesc, pntCnt, center, pnt, elementID, place, state)
{
  var latlng;
  var pnts = pnt.split(",");
  var idx = 0;
  var idxPrint = 0;
  var latlngs = [];
  var latlngsPrint =[];
  var marker;
    
  var printImage = 'http://maps.google.com/maps/api/staticmap?center=' + center + '&zoom=14&size=400x400&maptype=roadmap&format=png&path=color:0x0000ff|weight:5';
  for(i=0; i<pntCnt; i++)
  {
    latlngsPrint[i] = new GLatLng(pnts[idxPrint], pnts[idxPrint+1], true);
    printImage += '|' + pnts[idxPrint] + ',' + pnts[idxPrint+1];
    idxPrint = idxPrint + 2;
  }  
  printImage += '&sensor=false&key=ABQIAAAA9k26g8XMhjW26puIcLupsBRBbvhE4ZnyWZrWL-s_bP6LnlCf_xS0mtQsuv4_V89DnPAqoqRqdCCiTQ';
  document.getElementById("printImg").value= printImage;


  // construct polyline and static map
  var img = 'http://maps.google.com/maps/api/staticmap?center=' + center + '&zoom=14&size=180x180&maptype=roadmap&format=png&path=color:0x0000ff|weight:5';
  for(i=0; i<pntCnt; i++)
  {
    latlngs[i] = new GLatLng(pnts[idx], pnts[idx+1], true);
    img += '|' + pnts[idx] + ',' + pnts[idx+1];
    idx = idx + 2;
  }  
  img += '&sensor=false&key=ABQIAAAA9k26g8XMhjW26puIcLupsBRBbvhE4ZnyWZrWL-s_bP6LnlCf_xS0mtQsuv4_V89DnPAqoqRqdCCiTQ';
  document.getElementById('shareImg').value = img;
  
  var walkLink = "http://apps.facebook.com/shareawalk/walks.php?id="+id;
  //Share button
  var functionToCall = "showfeed('" + title + "','" + walkDesc + "','" + walkLink + "','"+ img + "')";  
  document.getElementById('share').setAttribute('onClick', functionToCall);
  
  //Invite button
  place += ", " + state;
  functionToCall = "eventInvite('" + title + "','" + walkDesc + "','" + walkLink + "','" + place + "','" + place + "')" ;
  document.getElementById('invite').setAttribute('onClick', functionToCall);
}

//Function to create a trail from data.xml
function addWalk(walkDesc, pntCnt, pnt, desc, photo, rtng, views, favs, zip, weather, location, slope) 
{
  var latlng;
  var latlngs = [];
  var pnts = pnt.split(",");
  var descs = desc.split(",");
  var photos = photo.split(",");
  var idx = 0;
  var marker;
  
  for(i=0; i<pntCnt; i++)
  {
    latlngs[i] = new GLatLng(pnts[idx], pnts[idx+1], true);
    if(descs[(idx/2)] != '' || photos[(idx/2)] != '')
    {
      map.addOverlay(createMarker(latlngs[i], descs[(idx/2)], photos[(idx/2)]));
    }
    idx = idx + 2;
  }
  
  // Add the walk to map
  var walk = new GPolyline(latlngs, "#ff0000", 4);
  map.setCenter( (walk.getBounds()).getCenter(), map.getBoundsZoomLevel(walk.getBounds()) );
  map.addOverlay(walk);
  
  // Can be used to insert a new vertex in the middle!
  // Probably out of scope now!
  GEvent.addListener(walk, "click", function(latlng) 
  {
    map.setCenter((walk.getBounds()).getCenter(), 15);
    alert('Can be used to insert a new vertex in the middle of the line.. for now it is out of scope.. Clicked at lat : ' + latlng.lat() + ', long : ' + latlng.lng());
  });
  
  // Description
  document.getElementById('walkDescriptionContent').innerHTML = '&nbsp;&nbsp;&nbsp;' + walkDesc;
  
  // Ratings
  rtng = Math.round(rtng);
  var title = new Array();
  title[0] = 'Not Rated'
  title[1] = 'Very Bad';
  title[2] = 'Bad';
  title[3] = 'Good';
  title[4] = 'Very Good';
  title[5] = 'Excellent!';
  var tempHTML = '<table align="center"><tbody><tr class="tableHeader">' +
                 '<td style="padding-right:25px;">Rating</td>' + 
                 '<td style="padding-right:25px;">Length</td>' +
                 '<td style="padding-right:25px;">Location</td>' +
                 '<td style="padding-right:25px;">Visited</td>' +
                 '<td style="padding-right:25px;">Favorited</td></tr>' +
                 '<tr><td><div id="rateMe" onMouseOver="Tip(\'' + title[rtng] + '\');" onMouseOut="UnTip();" >';
  
  for(i = 1; i <= 5; i++)
  {
    if(i <= rtng)
      tempHTML += '<a id="star_' + i + '" class="on"></a>';
    else
      tempHTML += '<a id="star_' + i + '"></a>';
  }

  tempHTML += '</td><td>' + (walk.getLength() * 0.000621371192).toFixed(2) + ' mi</td><td>' + zip + '</td>' +
              '<td><img id="visited" class="checkedNo" src="images/eyeNotVisited.png" onClick="checkElement(this);" onMouseOver="tipMouseOver(this);" onMouseOut="tipMouseOut(this);"/></td>' +
              '<td><img id="favourited" class="markedNo" src="images/favoriteNo.png" onClick="checkElement(this);" onMouseOver="tipMouseOver(this);" onMouseOut="tipMouseOut(this);"/></td></tr>' +
              '<tr class="tableHeader" style="border-top:1px solid #898989;"><td>Properties</td>';

  //tempHTML = 'weather ';
  switch(weather)
  {
    // Sunny
    case "0":
      tempHTML += '<td><img src="images/tagSun.png" width=24 height=24 onmouseover="Tip(\'Weather - Sun Safe\');this.src=\'images/tagSun2.png\';" onmouseout="UnTip();this.src=\'images/tagSun.png\';" style="margin-right:10px;margin-left:10px;"/></td>';
      break;
    // Snow Safe  
    case "1":
      tempHTML += '<td><img src="images/tagSnow.png" width=24 height=24 onmouseover="Tip(\'Weather - Snow Safe\');this.src=\'images/tagSnow2.png\';" onmouseout="UnTip();this.src=\'images/tagSnow.png\';" style="margin-right:10px;margin-left:10px;"/></td>';
      break;
    // Rain Safe  
    case "2":
      tempHTML += '<td><img src="images/tagRain.png" width=24 height=24 onmouseover="Tip(\'Weather - Rain Safe\');this.src=\'images/tagRain2.png\';" onmouseout="UnTip();this.src=\'images/tagRain.png\';" style="margin-right:10px;margin-left::10px;"/></td>';
      break;
  }
  
  switch(location)
  {
    // Downtown
    case "0":
      tempHTML += '<td><img src="images/tagCity.png" width=24 height=24 onmouseover="Tip(\'Location - City\');this.src=\'images/tagCity2.png\';" onmouseout="UnTip();this.src=\'images/tagCity.png\';" style="margin-right:10px;"/></td>';
      break;
    // Sub Urban
    case "1":
      tempHTML += '<td><img src="images/tagRain.png" width=24 height=24 onmouseover="Tip(\'Location - Sub Urban\');this.src=\'images/tagRain2.png\';" onmouseout="UnTip();this.src=\'images/tagRain.png\';" style="margin-right:10px;"/></td>';
      break;
    // Scenic  
    case "2":
      tempHTML += '<td><img src="images/tagRain.png" width=24 height=24 onmouseover="Tip(\'Location - Nature\');this.src=\'images/tagRain2.png\';" onmouseout="UnTip();this.src=\'images/tagRain.png\';" style="margin-right:10px;"/></td>';
      break;
  }
  
  switch(slope)
  {
    // Plains
    case "0":
      tempHTML += '<td><img src="images/tagPlain.png" width=24 height=24 onmouseover="Tip(\'Slope - Plains\');this.src=\'images/tagPlain2.png\';" onmouseout="UnTip();this.src=\'images/tagPlain.png\';"/></td>';
      break;
    // Gentle Slope
    case "1":
      tempHTML += '<td><img src="images/tagGentle.png" width=24 height=24 onmouseover="Tip(\'Slope - Gentle Slope\');this.src=\'images/tagGentle2.png\';" onmouseout="UnTip();this.src=\'images/tagGentle.png\';"/></td>';
      break;
    // Rugged
    case "2":
      tempHTML += '<td><img src="images/tagRugged.png" width=24 height=24 onmouseover="Tip(\'Slope - Rugged\');this.src=\'images/tagRugged2.png\';" onmouseout="UnTip();this.src=\'images/tagRugged.png\';"/></td>';
      break;
  }
  tempHTML += '<td></td></tr></tbody></table></div>';
  document.getElementById('ratings').innerHTML = tempHTML;
}

function checkElement(element)
{
  if(element.className == "checkedNo")
  {
    element.className = "checkedYes";
    element.src = 'images/eyeVisited.png';
    UnTip();
  }
  
  if(element.className == "markedNo")
  {
    element.className = "markedYes";
    element.src = 'images/favoriteYes.png';
    UnTip();
  }
}

function tipMouseOver(element)
{
  if(element.className == "checkedNo")
    Tip('Mark as visited');
  if(element.className == "checkedYes")
    Tip('You have visted this walk!');  
    
  if(element.className == "markedNo")
    Tip('Mark as favorite!');
  if(element.className == "markedYes")
    Tip('You have favorited this walk!');  
}

function tipMouseOut(element)
{
  UnTip();
}

function showAddress(address) 
{
	 var geocoder = new GClientGeocoder();
	 geocoder.getLatLng(address, function(point) 
	 {
		 if(!point)
		   alert(address + " not found.");
		 else
		 {
		   map.setCenter(point, 14);
		   alert("Lat : " + point.lat() + ", Long : " + point.lng());
		   this.addr.value = "Lat : " + point.lat() + ", Long : " + point.lng();
     }
	 });
}//showAddress

//Function to create a marker with the html description
function createMarker(latlng, strDesc, strPhoto) 
{
  var marker;
  var tempHTML = '<div style="width:205px;height:150px;">';
  
  if(strDesc != '')
    tempHTML += '<b>Description</b><br/>&nbsp;&nbsp;&nbsp;' + strDesc + '<br/>';
  if(strPhoto != '')
    tempHTML += '<a href="' + strPhoto + '" target="_blank"><img src="' + strPhoto + '" style="height:100px;" /></a></div>';
  
  if(strPhoto != '')
    marker = new GMarker(latlng, {icon:cameraIcon,draggable:false});
  else
    marker = new GMarker(latlng, {icon:redIcon,draggable:false});

  // Marker on click event  
  GEvent.addListener(marker, 'click', function() 
  {
    marker.openInfoWindowHtml(tempHTML,{noCloseOnClick:true,onOpenFn:function(){infoWindow.reset(this.getPoint(),infoWindow.getTabs(),new GSize(200,200),null,null);}});
    activeMarker = marker;
  });
  
  GEvent.addListener(map.getInfoWindow(),"closeclick", function()
  {
    activeMarker = null;
  });
  
  GEvent.addListener(marker, 'mouseover', function() 
  {
    if(map.getInfoWindow().isHidden() && activeMarker == null)
    {
      marker.openInfoWindowHtml(tempHTML,{onOpenFn:function(){infoWindow.reset(this.getPoint(),infoWindow.getTabs(),new GSize(200,200),null,null);}});
    } 
  });
  
  GEvent.addListener(marker, 'mouseout', function() 
  {
    if(activeMarker == null)
    {
      map.closeInfoWindow();
    } 
  });
  
  return marker;
}//createMarker

function savePhoto(strPhotoLink)
{
  alert('In Save Photo!' + strPhotoLink);
}

function saveDesc(strDesc)
{
  alert('In Save Desc!' + strDesc);
}

function clearText(element)
{
  element.value='';
}

function getURLParam(strParamName)
{
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 )
  {
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ )
    {
      if ( aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 )
      {
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
}

function search(strSearchKey)
{
  //if name search.. else geocode search
  var request = GXmlHttp.create();
  var id = -1;
  // Indicate Loading
  request.open('GET', 'mapWalks3.php?title='+strSearchKey, true);
  request.onreadystatechange = function() 
  {
    if (request.readyState == 4) 
    {
      if(request.responseText != '<walks></walks>')
      {
        xmlDoc = request.responseXML;
        if(xmlDoc != null)
        {
          walks = xmlDoc.documentElement.getElementsByTagName("walk");
          document.getElementById('searchContent').innerHTML = '';
          for (var i = 0; i < walks.length; i++) 
          {
            document.getElementById('searchContent').innerHTML += '<div class="listItem" id="listItem"><a href="javascript:updateWalks(' + walks[i].getAttribute("id") + ')" class="link">' + walks[i].getAttribute("title") + '</a></div>';
          }
          updateWalks(walks[0].getAttribute("id"));
        }
        else 
        {
          map.clearOverlays();
          document.getElementById('searchContent').innerHTML = '';
          map.setCenter(new GLatLng(44.976436, -93.232242), 12);
          alert('Something went wrong in getting the data.. try again!');
        }
      }
      else // No name search results
      {
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(strSearchKey, function(point) 
        {
          if(!point)
          {
            map.clearOverlays();
            document.getElementById('searchContent').innerHTML = '';
            map.setCenter(new GLatLng(44.976436, -93.232242), 12);
            alert('No walks found with the given search name (geocoder)!');
          }
          else
          {
            // Search for walks based on zip
            // reverse geocode
            geocoder.getLocations(point, function(response)
            {
              var zip = -1;
              if(response.Status.code == 200)
              {
                if(response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber != null)
                  zip = response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
                else if(response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber != null)
                  zip = response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber; 
              }
              
              if(zip != -1)
              {
                searchZip(zip);
              }
              else
              {
                map.clearOverlays();
                document.getElementById('searchContent').innerHTML = '';
                map.setCenter(new GLatLng(44.976436, -93.232242), 12);
                alert('Unable to get Zip code!!');
              }
            });
          }
        });
      }
    } 
  }
  // Stop Loading
  request.send(null);
}

function searchZip(zip)
{
  var request = GXmlHttp.create();
  // Indicate Loading
  request.open('GET', 'mapWalks4.php?zip='+zip, true);
  request.onreadystatechange = function() 
  {
    if (request.readyState == 4) 
    {
      if(request.responseText != '<walks></walks>')
      {
        xmlDoc = request.responseXML;
        if(xmlDoc != null)
        {
          walks = xmlDoc.documentElement.getElementsByTagName("walk");
          for (var i = 0; i < walks.length; i++) 
          {
            if(i==0)
            {
              map.clearOverlays();
              document.getElementById('searchContent').innerHTML = '';
              addWalk(walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("pnts"), walks[i].getAttribute("desc"), walks[i].getAttribute("photo"), walks[i].getAttribute("rtng"), walks[i].getAttribute("views"), walks[i].getAttribute("favs"), walks[i].getAttribute("zip"), walks[i].getAttribute("weather"), walks[i].getAttribute("location"), walks[i].getAttribute("slope"));
              updateButtons(walks[i].getAttribute("id"), walks[i].getAttribute("title"), walks[i].getAttribute("walkDesc"), walks[i].getAttribute("pntCnt"), walks[i].getAttribute("center"), walks[i].getAttribute("pnts"));
              showHideDeleteButton(walks[i].getAttribute("uid"));
               //document.getElementById('searchContent').innerHTML += '<div class="listItem" id="listItem"><a href="javascript:updateWalks(' + walks[i].getAttribute("id") + ')" class="link">' + walks[i].getAttribute("title") + '</a></div>';
            }
            document.getElementById('searchContent').innerHTML += '<div class="listItem" id="listItem"><a href="javascript:updateWalks(' + walks[i].getAttribute("id") + ')" class="link">' + walks[i].getAttribute("title") + '</a></div>';
          }
        }
        else
        {
          map.setCenter(new GLatLng(44.976436, -93.232242), 12);
          map.clearOverlays();
          document.getElementById('searchContent').innerHTML = '';
          alert('Error Loading Data from File! Please try again..');
        }
      }
      else
      {
        map.clearOverlays();
        document.getElementById('searchContent').innerHTML = '';
        map.setCenter(new GLatLng(44.976436, -93.232242), 12);
        alert('No walks found using zipcode!');
      }
    } 
  }
  request.send(null);
}
window.onload = init
window.onunload = GUnload
